package xworker.swt.app.view.swt.data.dialogs;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.util.UtilMap;
import xworker.dataObject.DataObject;
import xworker.swt.util.SwtUtils;
import xworker.lang.util.UtilData;

public class EditDataObjectDialog {
	public static Object update(Shell shell, Object dataStore, DataObject record, ActionContext parentContext) {
		try {
			if (dataStore instanceof xworker.dataObject.DataStore) {
				return ((xworker.dataObject.DataStore) dataStore).update(record);
			} else if (dataStore instanceof Thing) {
				return ((Thing) dataStore).doAction("update", parentContext, UtilMap.toMap("record", record));
			}
		} catch (Exception e) {
			MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
			box.setText(shell.getText());
			box.setMessage(e.getMessage());
			SwtUtils.showMessageBox(box, parentContext, null);
		}

		return null;
	}

	public static void okButtonAction(ActionContext actionContext){
		Thing form = (Thing) actionContext.get("form");
		Shell shell = (Shell) actionContext.get("shell");
		Object ds = actionContext.get("dataStore");
		ActionContext parentContext = (ActionContext) actionContext.get("parentContext");

		final DataObject result = form.doAction("getDataObject", actionContext);
		Object confirm = actionContext.get("confirm");
		String message = (String) actionContext.get("message");
		
		if(UtilData.isTrue(confirm) && message != null){
		    MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK |SWT.CANCEL);
		    box.setText(shell.getText());
		    box.setMessage(message);
			SwtUtils.showMessageBox(box, actionContext, returnCode -> {
				if(returnCode == SWT.OK){
					Object rs = update(shell, ds, result, parentContext);

					actionContext.getScope(0).put("result", rs);
					shell.dispose();
				}
			});
		}else {
			Object rs = update(shell, ds, result, parentContext);

			actionContext.getScope(0).put("result", rs);
			shell.dispose();
		}
	}
}
